package com.gitee.wsl.security.encrypt

object Pwd:StringToStringEncrypt {
    /**
     * 加密
     *
     * @param pwd
     * 源密码
     * @return 加密后的密码
     */
    override fun encrypt(pwd: String): String {
        val len = pwd.length
        val sb: StringBuilder = StringBuilder(2 * len + 2)
        for (i in 0 until len) {
            val c = pwd[i]
            sb.append(('a'.code + ((c.code ushr 12) and 0xf)).toChar())
            sb.append(('a'.code + ((c.code ushr 8) and 0xf)).toChar())
            sb.append(('a'.code + ((c.code ushr 4) and 0xf)).toChar())
            sb.append(('a'.code + (c.code and 0xf)).toChar())
        }
        return sb.toString()
    }

    /**
     * 解密
     *
     * @param pwd
     * 加密后的密码
     * @return 源密码
     */
    override fun decrypt(pwd: String): String {
        val len = pwd.length
        if (len % 4 != 0) throw RuntimeException("error encrypted password")
        val sb: StringBuilder = StringBuilder(len / 4)
        for (i in 0 until len / 4) {
            var c = (((pwd[4 * i].code - 'a'.code) and 0xf) shl 12).toChar()
            c += (((pwd[4 * i + 1].code - 'a'.code) and 0xf) shl 8).toChar().code
            c += (((pwd[4 * i + 2].code - 'a'.code) and 0xf) shl 4).toChar().code
            c += ((pwd[4 * i + 3].code - 'a'.code) and 0xf).toChar().code
            sb.append(c)
        }
        return sb.toString()
    }
}

val Encrypt.Companion.password get() = Pwd